import dayjs from "dayjs";
import { Ref, computed } from "vue";
import CommonHook from "@/hook/commonHook";
import { getPageStaticApi, cancelBatchOrderShipmentApi, listByBusinessIdApi } from "@/api/waybillManagement/businessWaybill/index";
import { getListApi, releaseCargoBatchApi, exportFinanceShipmentListApi } from "@/api/waybillManagement/financeWaybill/index";
import { shippingApi, signingApi, outWarehouseApi, statisticsDataApi } from "@/api/waybillManagement/customerServiceWaybill/index";
import { message, message as Message } from "ant-design-vue";
import printJs from "print-js";
import { printLabelApi } from "@/api/common";
export default function OperationHook(state: {
  activeKey: Ref<string>;
  searchForm: any;
  tableData: Ref<FinanceWaybill.ListRows[]>;
  drawerOpts: Base.DrawerOpts;
  dialogOpts: Base.DialogOpts;
  loading: Ref<boolean>;
  tableRef: any;
  saPageInfo: Base.GeneraDataType;
  pageStat: Base.GeneraDataType;
}) {
  const { activeKey, searchForm, tableData, drawerOpts, loading, tableRef, saPageInfo, dialogOpts, pageStat } = state;
  const selectRows = computed<Array<FinanceWaybill.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const { downloadFileByBlob } = CommonHook();
  const getData = async () => {
    const params = {
      ...getParams(),
      statusList: [Number(activeKey.value)],
      saPageInfo: saPageInfo.value
    };
    loading.value = true;
    return getListApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.total = Number(data.total);
          saPageInfo.value = data.saPageInfo || {};
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const pageStateic = () => {
    const params = getParams();
    loading.value = true;
    return getPageStaticApi({ ...params, statusList: [5, 6, 7, 8, 9, -5, 0, -2] })
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          Object.assign(pageStat.value, {
            5: data[5],
            6: data[6],
            7: data[7],
            8: data[8],
            9: data[9],
            "-5": data[-5],
            0: data[0],
            "-2": data[-2]
          });

          // activeKey.value = String(getNoZeroKey(pageStat.value, ["5", "6", "7", "8", "9", "-5", "0", "-2"]));
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const getParams = () => {
    const {
      keyWordsList,
      waybillNumList,
      fbaNumberList,
      transferOrderNumberList,
      bizIdList,
      followIdList,
      channelIdList,
      markList,
      notMark,
      customerIdList,
      makeInvoiceStatus,
      zipCode,
      countryRegionIdList,
      customsTaxesTypeList,
      customsDeclarationType,
      innerRemark,
      remark,
      depositTime,
      createdTime,
      warehouseCodeList,
      pageNum,
      pageSize
    } = searchForm;
    const params: any = {
      waybillNumList: [],
      keyWordsList: [],
      fbaNumberList: [],
      transferOrderNumberList: [],
      bizIdList,
      followIdList,
      channelIdList,
      warehouseCodeList,
      remark,
      markList,
      notMark,
      customerIdList,
      makeInvoiceStatus,
      zipCode,
      countryRegionIdList,
      customsTaxesTypeList,
      customsDeclarationType,
      innerRemark,
      startTime: createdTime.length ? dayjs(createdTime[0]).startOf("day").format("YYYY-MM-DD HH:mm:ss") : undefined,
      endTime: createdTime.length ? dayjs(createdTime[1]).endOf("day").format("YYYY-MM-DD HH:mm:ss") : undefined,
      depositStartTime: depositTime.length ? dayjs(depositTime[0]).startOf("day").format("YYYY-MM-DD HH:mm:ss") : undefined,
      depositEndTime: depositTime.length ? dayjs(depositTime[1]).endOf("day").format("YYYY-MM-DD HH:mm:ss") : undefined,
      pageNum,
      pageSize
    };
    if (waybillNumList)
      params.waybillNumList = waybillNumList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (keyWordsList)
      params.keyWordsList = keyWordsList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (fbaNumberList)
      params.fbaNumberList = fbaNumberList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (transferOrderNumberList)
      params.transferOrderNumberList = transferOrderNumberList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (channelIdList.length) {
      params.channelIdList = channelIdList.map((t: any) => t[t.length - 1]);
    }
    if (searchForm.sort) {
      params.order = searchForm.order;
      params.sort = searchForm.sort;
    }
    return params;
  };
  const searchHandle = async () => {
    searchForm.pageNum = 1;
    await pageStateic();
    getData();
  };
  const changeTabHandle = () => {
    searchForm.pageNum = 1;
    getData();
  };
  const showHandle = (row: ClientWaybillManagement.ListRows) => {
    drawerOpts.title = `查看(${row.waybillNum})`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "Details";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  // 更改渠道
  const modifyChannelHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    if (selectRows.value.length > 1) return Message.error("只能勾选1条运单!");
    dialogOpts.title = `修改渠道`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ModifyChannel";
    dialogOpts.passData = selectRows.value[0];
    dialogOpts.visible = true;
  };

  // 更改代理渠道
  const modifyAgentChannelHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    if (selectRows.value.length > 1) return Message.error("只能勾选1条运单!");
    dialogOpts.title = `更改代理渠道`;
    dialogOpts.width = "520px";
    dialogOpts.component = "ModifyAgentChannel";
    dialogOpts.passData = selectRows.value[0];
    dialogOpts.visible = true;
  };

  // 修改品名
  const modifyProductNameHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    if (selectRows.value.length > 1) return Message.error("只能勾选1条运单!");
    if (selectRows.value[0].makeInvoiceStatus === -2) return Message.error("请修改运单发票内材质！");
    dialogOpts.title = `修改品名`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ModifyProductName";
    dialogOpts.passData = selectRows.value[0];
    dialogOpts.visible = true;
  };
  // 修改材质
  const modifyMasterialHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    if (selectRows.value.length > 1) return Message.error("只能勾选1条运单!");
    if (selectRows.value[0].makeInvoiceStatus === -2) return Message.error("请修改运单发票内材质！");
    dialogOpts.title = `修改材质`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ModifyMasterial";
    dialogOpts.passData = selectRows.value[0];
    dialogOpts.visible = true;
  };
  // 修改客户备注
  const modifyRemarkHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    dialogOpts.title = `修改客户备注`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ModifyRemark";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };

  // 批量修改转单号
  const transferNumberHandle = () => {
    dialogOpts.title = `批量修改转单号`;
    dialogOpts.width = "1000px";
    dialogOpts.component = "TransferNumber";
    dialogOpts.visible = true;
  };

  // 设置转单号
  const setTransferNumberHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    if (selectRows.value.length > 1) return Message.error("只能勾选1条运单!");
    dialogOpts.title = `设置转单号`;
    dialogOpts.width = "520px";
    dialogOpts.component = "SetTransferNumber";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };

  // 操作标识
  const modifyMarkHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    dialogOpts.title = `标识`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "Mark";
    dialogOpts.passData = selectRows.value[0];
    dialogOpts.visible = true;
  };

  // 修改客户备注
  const modifyInnerRemarkHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    dialogOpts.title = `修改内部备注`;
    dialogOpts.width = "520px";
    dialogOpts.type = 2;
    dialogOpts.component = "ModifyRemark";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };
  // 批量添加轨迹
  const addRouteInfoHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    dialogOpts.title = `批量添加轨迹`;
    dialogOpts.width = "520px";
    dialogOpts.component = "RouteInfo";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };

  // 批量导入轨迹
  const importRouteInfoHandle = () => {
    dialogOpts.title = `批量导入轨迹`;
    dialogOpts.width = "520px";
    dialogOpts.component = "ImportRouteInfo";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };

  // 取消运单
  const cancelShipmentHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    const ids = selectRows.value.map((t: any) => t.id);

    cancelBatchOrderShipmentApi(ids).then((res: any) => {
      const { code, data } = res;
      if (code === 200 && data === "取消成功") {
        Message.success("操作成功!");
        getData();
        pageStateic();
      }
    });
  };

  // 退件
  const returnOrderHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    dialogOpts.title = `退件`;
    dialogOpts.width = "520px";
    dialogOpts.component = "ReturnOrder";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };

  //流程状态
  const statusHandle = (status: number) => {
    // 2出库 3出运 4签收     出仓单独控制
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    const params: CustomerServiceWaybill.StaHandle = {
      idList: selectRows.value.map((t: any) => t.id)
    };
    let request: any;

    if (status === 2) {
      request = outWarehouseApi;
    }

    if (status === 3) {
      request = shippingApi;
    }

    if (status === 4) {
      request = signingApi;
    }

    request(params).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        Message.success("操作成功!");
        searchHandle();
      }
    });
  };

  //出库
  const outOfWarehouseHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    dialogOpts.title = `出库`;
    dialogOpts.width = "520px";
    dialogOpts.component = "OutOfWarehouse";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };
  // 获取统计数据
  const getStatisticsDataFn = () => {
    const params: any = {
      ...getParams(),
      statusList: [Number(activeKey.value)],
      saPageInfo: saPageInfo.value
    };
    if (selectRows.value.length) params.idList = selectRows.value.map((t: CustomerServiceWaybill.ListRows) => t.id);
    return statisticsDataApi(params).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        dialogOpts.passData = data || {};
      }
    });
  };
  // 查看统计
  const showStatictisHandle = () => {
    dialogOpts.title = "查看统计";
    dialogOpts.width = "900px";
    dialogOpts.component = "DataStatistics";
    dialogOpts.visible = true;
  };
  //制作发票
  const makeInvoiceHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    if (selectRows.value.length > 1) return Message.error("只能勾选1条运单!");
    if (selectRows.value[0].makeInvoiceStatus === -2) return Message.error("只能操作未制作发票的数据!");
    drawerOpts.title = `制作发票`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "MakeInvoice";
    drawerOpts.passData = selectRows.value[0];
    drawerOpts.visible = true;
  };

  // 使用模版导出
  const templateExportHandle = () => {
    dialogOpts.title = `模版导出`;
    dialogOpts.width = "520px";
    dialogOpts.component = "TemplateExport";
    dialogOpts.type = Number(activeKey.value);
    dialogOpts.passData = getParams();
    dialogOpts.visible = true;
  };
  // 自定义模版导出
  const customExportHandle = () => {
    dialogOpts.title = `自定义模版导出`;
    dialogOpts.width = "800px";
    dialogOpts.component = "CustomExport";
    dialogOpts.type = Number(activeKey.value);
    dialogOpts.passData = getParams();
    dialogOpts.visible = true;
  };
  // 打印
  const printLabelHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    loading.value = true;
    printLabelApi({ idList: selectRows.value.map((t: ClientAdvanceManagement.ListRows) => t.id), type: 2 })
      .then((res: any) => {
        if (res.headers["content-type"] === "application/json") {
          const reader = new FileReader(); //创建一个FileReader实例
          reader.readAsText(res.data, "utf-8"); //读取文件,结果用字符串形式表示
          reader.onload = () => {
            //读取完成后,**获取reader.result**
            const { message } = JSON.parse(reader.result as string);
            Message.error(message); //弹出错误提示
          };
        } else {
          const pdfUrl = window.URL.createObjectURL(res.data);
          printJs({ printable: pdfUrl, type: "pdf" });
        }
      })
      .finally(() => (loading.value = false));
  };
  // 下载标签
  const downloadLabelHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    loading.value = true;
    printLabelApi({ idList: selectRows.value.map((t: ClientAdvanceManagement.ListRows) => t.id), type: 2 })
      .then((res: any) => {
        if (res.headers["content-type"] === "application/json") {
          const reader = new FileReader(); //创建一个FileReader实例
          reader.readAsText(res.data, "utf-8"); //读取文件,结果用字符串形式表示
          reader.onload = () => {
            //读取完成后,**获取reader.result**
            const { message } = JSON.parse(reader.result as string);
            Message.error(message); //弹出错误提示
          };
        } else {
          downloadFileByBlob(res.data, "标签.pdf", "application/pdf");
        }
      })
      .finally(() => (loading.value = false));
  };
  //日志
  const showLogHandle = (row: WarehouseEntryChannel.ListRows) => {
    drawerOpts.title = "日志";
    drawerOpts.width = "1200px";
    drawerOpts.passData = row;
    drawerOpts.component = "OperationLog";
    drawerOpts.type = 2;
    drawerOpts.visible = true;
  };

  const requestFn = () => {
    return listByBusinessIdApi({ businessId: drawerOpts.passData?.id, sysModule: "运单管理" });
  };
  // 发票导出
  const invoiceExportHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    if (selectRows.value.length > 1) return Message.error("每次只能导出一条运单的发票!");
    const index = selectRows.value.findIndex((t: BusinessWaybill.ListRows) => t.makeInvoiceStatus === -1);
    if (index !== -1) return Message.error("只能勾选已制作发票的运单!");
    dialogOpts.title = "发票导出";
    dialogOpts.width = "520px";
    dialogOpts.passData = selectRows.value[0];
    dialogOpts.component = "InvoiceExport";
    dialogOpts.visible = true;
  };
  // 扣货
  const detainGoodsHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    // Modal.confirm({
    //   title: "是否将勾选的运单进行扣货?",
    //   icon: createVNode(ExclamationCircleOutlined),
    //   onOk() {
    //     batchDetainGoodsApi(selectRows.value.map((t: BusinessWaybill.ListRows) => t.id)).then((res: any) => {
    //       const { code } = res;
    //       if (code === 200) {
    //         message.success("扣货成功!");
    //         getData();
    //         pageStateic();
    //       }
    //     });
    //   }
    // });

    dialogOpts.title = `扣货原因`;
    dialogOpts.width = "520px";
    dialogOpts.component = "DetainGoods";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };
  // 代理状态标记
  const agentStatusSignHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    dialogOpts.title = `代理状态标记`;
    dialogOpts.width = "520px";
    dialogOpts.component = "AgentStatusSign";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };
  // 放货
  const releaseCargoHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    return releaseCargoBatchApi(selectRows.value.map((t: BusinessWaybill.ListRows) => t.id)).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("放货成功!");
        getData();
        pageStateic();
      }
    });
  };
  //导出
  const exportHandle = () => {
    const params = {
      ...getParams(),
      idList: selectRows.value.length ? selectRows.value.map((t: any) => t.id) : undefined,
      statusList: [Number(activeKey.value)]
    };
    return exportFinanceShipmentListApi(params).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("创建任务成功，请前往导出中心下载！!");
      }
    });
  };
  //问题件
  const addProblemShipment = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    if (selectRows.value.length > 1) return Message.error("一次勾选最多1条!");
    if (selectRows.value[0].status === 0) return Message.error("取消的运单不可发起问题件!");

    drawerOpts.title = `发起问题件`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "ProblemShipment";
    drawerOpts.passData = selectRows.value[0];
    drawerOpts.visible = true;
  };

  return {
    searchHandle,
    getData,
    showHandle,
    changeTabHandle,
    modifyChannelHandle,
    modifyMasterialHandle,
    modifyProductNameHandle,
    modifyRemarkHandle,
    modifyInnerRemarkHandle,
    modifyMarkHandle,
    transferNumberHandle,
    setTransferNumberHandle,
    addRouteInfoHandle,
    importRouteInfoHandle,
    cancelShipmentHandle,
    returnOrderHandle,
    statusHandle,
    outOfWarehouseHandle,
    getStatisticsDataFn,
    showStatictisHandle,
    makeInvoiceHandle,
    templateExportHandle,
    customExportHandle,
    printLabelHandle,
    downloadLabelHandle,
    modifyAgentChannelHandle,
    requestFn,
    showLogHandle,
    invoiceExportHandle,
    detainGoodsHandle,
    agentStatusSignHandle,
    releaseCargoHandle,
    exportHandle,
    addProblemShipment
  };
}
